
var pkg = "firewall";
var homeuserprefix = "Homeuser_";
var currentuser;
var ruleType = "whitelist_rule";
var homeuserMac;

function parseArp(arpLines)
{
	var arpHash = [];
	
	arpLines.shift(); //skip header
	var lineIndex = 0;
	for(lineIndex=0; lineIndex < arpLines.length; lineIndex++)
	{
		var nextLine = arpLines[lineIndex];
		var splitLine = nextLine.split(/[\t ]+/);
		var mac = splitLine[3].toUpperCase();
		var ip = splitLine[0];
		arpHash[ mac ] = ip;
		arpHash[ ip  ] = mac;
	}

	return arpHash;
}

function doHomeuseractive()
{
	var myDate = new Date(currentTime*1000);
	var myHour = myDate.getHours();
	var myMinute = myDate.getMinutes();
	if(myMinute < 10){ myMinute = "0" + myMinute;}
	Userloggedin = true;
	MacAddrs = homeuserMac.replace(/^[\t ]*/, "");
	MacAddrs = homeuserMac.replace(/[\t ]*$/, "");
	uci.set("gargoyle",currentuser,"Maclist_str",MacAddrs);
	//var addrs = MacAddrs.split(/[\t ]*,[\t ]*/);
	/*var table = tableContainer.childNodes.length > 0 ? tableContainer.firstChild : createTable([""], [], "exception_applies_to_table" , true, false);
	while(addrs.length > 0)
		{
			addTableRow(table, [ addrs.shift() ], true, false);
		}
	if(tableContainer.childNodes.length == 0)
		{
			tableContainer.appendChild(table);
		}
	*/
	currentDay = currentDay.toLowerCase();
	var sectionId = "Homecafe_allow";
	var rulePrefix = "exception_";
	var runCommands = [];	
	var userID = document.getElementById("userID").value;
	var deleteSectionCommands = [];
	var createSectionCommands = [];		
	var userlefthours =  uci.get("gargoyle",currentuser,"hourlimit_"+currentDay) == "" ? 24 : uci.get("gargoyle",currentuser,"hourlimit_"+currentDay) ;
	var exceptionlist = uci.getAllSectionsOfType(pkg,ruleType);
	for(exceptionIndex=0;exceptionIndex < exceptionlist.length;exceptionIndex++)
	{
	ruleID = exceptionlist[exceptionIndex];
	if(uci.get(pkg,ruleID,"description")==userID)
	{   
	uciOriginal.removeSection(pkg,ruleID);
	uci.removeSection(pkg,ruleID);
	deleteSectionCommands.push("uci del " + pkg + "." + ruleID);	
	}
	}
	
	var newexceptionlist = uci.getAllSectionsOfType(pkg,ruleType);
	var number = (newexceptionlist.length+1) ;
	var activetimestr =  uci.get("gargoyle",currentuser, currentDay + "_activetime");
	var activetimelist = activetimestr.split(/,/);
	var enabledhours = 0;
	if(activetimestr != "")
		{
		//for each activetime period.Set exceptions.
		for(timeIndex=0;timeIndex < activetimelist.length;timeIndex++)
			{
			if(enabledhours < userlefthours)
			{
			activehour = (activetimelist[timeIndex]-1);
				if(activehour > myHour)
				{
				
				ruleID = rulePrefix + number;
				number++;
				uci.set(pkg,ruleID,ruleType);
				createSectionCommands.push("uci set " + pkg + "." + ruleID + "='" + ruleType + "'");
				createSectionCommands.push("uci commit");
				uci.set(pkg,ruleID,"local_addr",MacAddrs);
				uci.set(pkg,ruleID,"description",userID);
				uci.set(pkg,ruleID,"active_weekdays",currentDay);
				uci.set(pkg,ruleID,"is_ingress",0);
				uci.set(pkg,ruleID,"enabled",1);
				uci.set(pkg,ruleID,"active_hours", activehour+":00-"+(activehour+1)+":00");
				enabledhours++;
				expirehour = (activehour+1)+":00";
				}
				else
				{
				if(activehour == myHour)
					{
					ruleID = rulePrefix + number;
					number++;
					uci.set(pkg,ruleID,ruleType);
					createSectionCommands.push("uci set " + pkg + "." + ruleID + "='" + ruleType + "'");
					createSectionCommands.push("uci commit");
					uci.set(pkg,ruleID,"local_addr",MacAddrs);
					uci.set(pkg,ruleID,"description",userID);
					uci.set(pkg,ruleID,"active_weekdays",currentDay);
					uci.set(pkg,ruleID,"is_ingress",0);
					uci.set(pkg,ruleID,"enabled",1);
					uci.set(pkg,ruleID,"active_hours", activehour+":" + myMinute + "-"+(activehour+1)+":00");
					enabledhours++;	
					expirehour = (activehour+1)+":00";
					}
				}
			}
			else
				{
				if(enabledhours == userlefthours)
					{
					activehour = (activetimelist[timeIndex]-1);
					ruleID = rulePrefix + number;
					uci.set(pkg,ruleID,ruleType);
					createSectionCommands.push("uci set " + pkg + "." + ruleID + "='" + ruleType + "'");
					createSectionCommands.push("uci commit");
					uci.set(pkg,ruleID,"local_addr",MacAddrs);
					uci.set(pkg,ruleID,"description",userID);
					uci.set(pkg,ruleID,"active_weekdays",currentDay);
					uci.set(pkg,ruleID,"is_ingress",0);
					uci.set(pkg,ruleID,"enabled",1);
					uci.set(pkg,ruleID,"active_hours", activehour+":00-"+activehour+":" + myMinute);
					enabledhours++;	
					expirehour = activehour + ":" + myMinute;
					}
				}
			}
		}
	uci.set("gargoyle",currentuser,"expire_hour",expirehour);
	uci.set("gargoyle",currentuser,"lastlogin",currentDay);
	setControlsEnabled(false, true,"Home User Logging In");
	

	var commands = deleteSectionCommands.join("\n") + "\n" + createSectionCommands.join("\n") + "\n" + uci.getScriptCommands(uciOriginal) + "\n" + "sh /usr/lib/gargoyle/restart_firewall.sh";

	var param = getParameterDefinition("commands", commands);

	var stateChangeFunction = function(req)
	{
		if(req.readyState == 4)
		{	
			setControlsEnabled(true);
			Homeusercountdown(userID);			
			//alert("You successfully logged in!");
		}
	}
	runAjax("POST", "utility/run_home_commands.sh", param, stateChangeFunction);
}



function Homeusercountdown(userID)
{
	document.getElementById("counter_down_timer").style.display = "block";
	setChildText("current_homeuser",userID);
	TimeID = "User_expire_time";
	expirehour = uci.get("gargoyle",currentuser,"expire_hour");
	setChildText(TimeID,expirehour);
	/*TimerID = "User_time_left";
	var Limit_time_second = 0;
	var Hours = 0;
	var Minutes = 5;
	Limit_time_second += Hours * (3600);
	Limit_time_second += Minutes * (60);
	CreateTimer(TimerID,Limit_time_second);*/
	
}

/*var TotalSeconds;
var Timer;

function CreateTimer(TimerID, Time) {
    Timer = TimerID;
    TotalSeconds = Time;
    
    UpdateTimer();
    window.setTimeout("Tick()", 1000);
}

function Tick() {
    if (TotalSeconds <= 0) {
        alert("Time's up!")
        return;
    }

    TotalSeconds -= 1;
    UpdateTimer()
    window.setTimeout("Tick()", 1000);
}

function UpdateTimer() {
    var Seconds = TotalSeconds;
    
    var Days = Math.floor(Seconds / 86400);
    Seconds -= Days * 86400;

    var Hours = Math.floor(Seconds / 3600);
    Seconds -= Hours * (3600);

    var Minutes = Math.floor(Seconds / 60);
    Seconds -= Minutes * (60);


    var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)


    setChildText(Timer,TimeStr);
}


function LeadingZero(Time) {

    return (Time < 10) ? "0" + Time : + Time;

}*/

function doHomeUserLogin()
{
	var userID = document.getElementById("userID").value;
	var userpassword = document.getElementById("userpassword").value;
	if(userID.length == 0 || userpassword.length == 0)
		{
			alert("ERROR: You must enter a Home user ID/password");
		}
	else
	{
	var HomeuserList =  uciOriginal.getAllSectionsOfType("gargoyle","Homeuser");
	for (homeuserIndex=0;homeuserIndex < HomeuserList.length;homeuserIndex++)
	{
		if(userID == uciOriginal.get("gargoyle",HomeuserList[homeuserIndex],"userID"))
		{
			if(userpassword == uciOriginal.get("gargoyle",HomeuserList[homeuserIndex],"password"))
				{
				currentuser = HomeuserList[homeuserIndex];
				if(uciOriginal.get("gargoyle",currentuser,"blocked") == "yes")
				{alert("You are blocked. Ask the parent account user for more information.");}
				else
				{var Ishomeuser = true;}
				}
		}
	}
	if(Ishomeuser)
		{
			homepassInvalid=false;
			Lastlogin = uciOriginal.get("gargoyle",currentuser,"lastlogin");
			currentDay = currentDay.toLowerCase();
			var arpHash = parseArp(arpLines);
			homeuserMac = arpHash[ connectedIp ];
			var Maclist = [];
			if(Lastlogin == currentDay)
			{
					var macexist = false;
					Currentusermacstr = uci.get("gargoyle",currentuser,"Maclist_str");
					Maclist = Currentusermacstr.split(/,/);
					for(macindex=0;macindex < Maclist.length;macindex++)
					{
					if(Maclist[macindex] == homeuserMac){macexist = true;}	
					}
					if(macexist == false)
						{
						Macliststr = Currentusermacstr + ","+ homeuserMac;
						uci.set("gargoyle",currentuser,"Maclist_str",Macliststr);
						var exceptionlist = uci.getAllSectionsOfType(pkg,ruleType);
						for(exceptionIndex=0;exceptionIndex < exceptionlist.length;exceptionIndex++)
							{
							ruleID = exceptionlist[exceptionIndex];
							if(uci.get(pkg,ruleID,"description")==userID)
								{   
								uci.set(pkg,ruleID,"local_addr",Macliststr);
								}
							}
						
						setControlsEnabled(false, true,"Home User Logging In");
	

						var commands = uci.getScriptCommands(uciOriginal) + "\n" + "sh /usr/lib/gargoyle/restart_firewall.sh";

						var param = getParameterDefinition("commands", commands);

						var stateChangeFunction = function(req)
						{
							if(req.readyState == 4)
							{	
								setControlsEnabled(true);
								Homeusercountdown(userID);			
								//alert("You successfully logged in!");
							}
						}
						runAjax("POST", "utility/run_home_commands.sh", param, stateChangeFunction);
						}
						else
						{Homeusercountdown(userID);}
			}
			else
			{
			doHomeuseractive();
			}		
		}
	else
		{
        		homepassInvalid=true;
			setHomeUserStatusAndQuotas();
		}
	}
}

function setHomeUserStatusAndQuotas()
{ 
        if(homepassInvalid)
	{
		setChildText("homeuser_login_status", "Invalid User ID Or get blocked", "red");
	}
}




